package com.huatai.bpmn.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.huatai.bpmn.constant.MinioBucket;
import com.huatai.bpmn.entity.FileEntity;
import com.huatai.bpmn.entity.UrgeCheckEntity;
import com.huatai.bpmn.entity.dto.CandidateTaskDto;
import com.huatai.bpmn.entity.dto.CompletionDto;
import com.huatai.bpmn.entity.dto.PageDto;
import com.huatai.bpmn.entity.vo.HistoryVO;
import com.huatai.bpmn.entity.vo.TaskManageVo;
import com.huatai.bpmn.entity.vo.UserTaskVo;
import com.huatai.bpmn.entity.vo.YYTaskVo;
import com.huatai.bpmn.service.*;
import com.huatai.bpmn.utils.Activiti7Util;
import com.huatai.common.api.R;
import com.huatai.common.config.MinioAPI;
import com.huatai.common.entity.UserInfo;
import com.huatai.common.util.AuthUtil;
import com.huatai.user.entity.Department;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.codec.language.Nysiis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: nzj
 * @Date: 2023/7/7 11:03
 */
@RestController
@RequestMapping("/yyActiviti")
@Api(value = "新-activiti流程控制", tags = "新-activiti流程控制")
public class YYActivitiController {
	@Autowired
	private BasicLoadService basicLoadService;

	@Autowired
	private YYActivitiService yyActivitiService;


	@Autowired
	private BasicDataService basicDataService;

	@Autowired
	private FileService fileService;

	@Autowired
	private MinioAPI minioAPI;

	@Autowired
	private ExternalParameterService externalParameterService;

	/**
	 * 部署流程定义 文件上传方式部署流程定义  shangji商机 ruku入库 shishi实施
	 * @param file bpmn文件
	 * @param deployName 部署名称
	 * @param externalParameterId 绑定表单标识
	 * @return
	 * @throws IOException
	 */
	@PostMapping("/deploy")
	@ApiOperation("部署流程定义,文件上传方式部署流程定义-目前只存在商机-入库-实施项目")
	public R<Map<String, Object>> deployment(@RequestBody MultipartFile file, @RequestParam String deployName,
								 @RequestParam String externalParameterId,@RequestParam int type) throws IOException {
		return yyActivitiService.deploy(file,deployName,externalParameterId,type);
	}

	@GetMapping("deleteDeploy/{id}")
	@ApiOperation("强制删除已部署流程定义")
	public R deleteDeploy(@PathVariable String id){
		return R.data(yyActivitiService.deleteDeploy(id));
	}

	@PostMapping("getDeployList")
	@ApiOperation("查看部署流程集合")
	@ApiOperationSupport(includeParameters = {
		"pageDto.page",
		"pageDto.limit"
	})
	public  R<Map<String, Object>> getDeployList(@RequestBody PageDto pageDto) {
		return yyActivitiService.getDeployList(pageDto);
	}

	@PostMapping("/definition")
	@ApiOperation("创建流程定义")
	public  R startProcess(@RequestBody JSONObject jsonObject){
		String businessKey = jsonObject.getOrDefault("businessKey", "").toString();
		return R.data(yyActivitiService.startProcess(jsonObject,businessKey));
	}

	@ApiOperation("文件上传")
	@PostMapping("/upload")
	public R uploadFile(@ApiParam(name = "file", value = "文件上传字段", required = true) MultipartFile file){
		try {
			minioAPI.makeBucket(MinioBucket.BPMN_FILES);
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
			LocalDate now = LocalDate.now();
			String dateFormat = now.format(formatter);
			//给文件和图片重新命名
			FileEntity fileEntity = new FileEntity();
			long id = IdWorker.getId(fileEntity);
			String fileName = dateFormat+"/"+ id + file.getOriginalFilename();
			minioAPI.uploadInputStream(MinioBucket.BPMN_FILES, fileName, file.getInputStream(), file.getContentType());
			return R.data(fileName);
		}catch (Exception e){
			return R.fail("文件上传失败");
		}
	}

	@ApiOperation("文件删除")
	@PostMapping("/fileDelete")
	public R fileDelete( String url){
		try {
			yyActivitiService.fileDelete(url);
			return R.success("删除成功");
		}catch (Exception e){
			return R.fail("文件上传失败");
		}
	}

	@GetMapping("/findToDoTask")
	@ApiOperation("查询待办任务列表")
	public R<List<YYTaskVo>> findToDoTask(@RequestParam String myKey){
		UserInfo localUser = AuthUtil.getUser();
		List<YYTaskVo> list=yyActivitiService.findToDoTask(myKey,localUser.getUserId().toString());
		return R.data(list);
	}

	@GetMapping("/findToDoTaskCount")
	@ApiOperation("查询待办任务列表-所有任务总数")
	public R findToDoTaskCount(){
		UserInfo user = AuthUtil.getUser();
		HashMap<String, Object> map = yyActivitiService.findToDoTaskCount(user.getUserId().toString());
		return R.data(map);
	}

	@ApiOperation("完成任务")
	@PostMapping("/completeTask")
	public  R completionTask(@RequestBody CompletionDto completionDto){
		boolean flag= yyActivitiService.completionTask(completionDto);
		return flag? R.success("操作成功"): R.fail("操作失败");
	}



	@PostMapping("/taskHistoryInfo/{processId}")
	@ApiOperation("查看流程实例的历史处理信息")
	public R<Map<String, List<HistoryVO>>> taskHistoryInfo(@PathVariable String processId){
		return R.data(yyActivitiService.taskHistoryInfo(processId));
	}

	@GetMapping("/findCompleteTask/{processId}")
	@ApiOperation("查询已办任务列表")
	public R<List<HistoricActivityInstance>> findCompleteTask(@PathVariable String processId){
		return R.data(yyActivitiService.findCompleteTask(processId));
	}

	@GetMapping("/findTaskByUser")
	@ApiOperation("查询当前用户发起的任务")
	public R<List<UserTaskVo>> findTaskByUser(){
		return R.data(yyActivitiService.findTaskByUser());
	}

	@GetMapping("/projectAudit")
	@ApiOperation("市场部端-项目审核情况，可一键催促")
	public R<HashMap<String, ArrayList<TaskManageVo>>> projectAudit(){
		return R.data(yyActivitiService.projectAudit());
	}

	@PostMapping("/urge")
	@ApiOperation("一键催促-可以催促多个")
	public R urge(@RequestBody List<TaskManageVo> taskManageVos){
		return R.data(yyActivitiService.urge(taskManageVos));
	}

	@GetMapping("/getUrgeTask")
	@ApiOperation("获取当前用户的催办任务")
	public R<List<UrgeCheckEntity>> getUrgeTask(){
		return R.data(yyActivitiService.getUrgeTask());
	}

	@GetMapping("/finishTask/{id}")
	@ApiOperation("催办任务已读")
	public R finishTask(@PathVariable Long id){
		return R.data(yyActivitiService.finishTask(id));
	}
}
